// pages/detail/detail.js
var utils = require("../../utils/util.js")

var pageSize = 30;
var pageIndex = 0;
var tid = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: null, //详情数据
    pubdate: null,
    releaseFocus: false,
    textareaDisplay: 'none',

    inqueue: null, // 排队中的数据

    praise: null, // 点赞列表
    praiseName: null,
    isLiked: false,

    queueSuccess: false, //排队成功

    selectorArr: ['1Kg以内', '1Kg～2Kg', '2Kg~3Kg', '3Kg~4Kg', '4Kg~5Kg'],
    selectorValue: 0
  },

  // 图片预览
  previewImage: function (e) {
    console.log(e)
    var that = this;
    var urls = that.data.data.imageList.map(function(v,i,arr){
      return v.src
    })
    wx.previewImage({
      current: e.target.dataset.src,
      urls: urls,
    })
  },
  


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    tid = options.id;

    /// 获取详情数据
    this.getForumDetail();

    // 获取点赞信息
    this.getForumPraise();

    /// 获取排队中
    this.queueGet();

  },

  getForumDetail: function () {
    var that = this;
    /// 获取详情数据
    wx.showLoading()
    console.log("id:" +tid + "userId:" + getApp().globalData.userInfo.userId);
    wx.request({
      url: getApp().globalData.getHomeForumDetail_url,
      data: {
        id: tid,
        userId: getApp().globalData.userInfo.userId,
      },
      success(res) {
        console.log(res);
        console.log("详情");
        that.setData({
          data: res.data.data,
          pubdate: utils.formatDate(parseInt(res.data.data.dateline)*1000, 'MM-dd')
        })
        var leftTime = res.data.data.endTime - res.data.data.current;
        console.log(leftTime)
        that.countDown(leftTime);
        if (res.data.data.status == 1 || res.data.data.status == 3) {
          that.setData({
            countDownTime: '--:--:--',
          })
        }
      },
      complete() {
        wx.hideLoading()
      }
    })
  },


  // 获取点赞信息
  getForumPraise: function () {
    var that = this;
    wx.request({
      url: getApp().globalData.getForumPraise_url + tid,
      success(res) {
        console.log(res)
        var names = res.data.data.praise.map(function (value, index, array) {
          return value.username;
        }).join(",")

        that.setData({
          praise: res.data.data.praise,
          praiseName: names,
        })
      }
    })
  },

  queueGet: function () {
    var that = this;
    // 获取排队中

    console.log(getApp().globalData.userInfo.userId, tid, getApp().globalData.acid, pageSize, pageIndex)
    wx.request({
      url: getApp().globalData.lineup_url,
      data: {
        userId: getApp().globalData.userInfo.userId,
        tid: tid,
        pageSize: pageSize,
        pageIndex: pageIndex
      },
      success(res) {
        console.log(res);
        console.log("排队中：");
        that.inqueue = res.data.data;
        var originlist = that.inqueue.list;
        that.newlist = originlist.filter(function (e, i, arr) {
          console.log(that.inqueue.userId != e.userId);
          return that.inqueue.userId != e.userId;
        })
        var threelist = that.newlist.slice(0, 2)
        console.log(threelist);
        that.inqueue.list = threelist;

        that.setData({
          inqueue: that.inqueue,
          inqueueOriginList: originlist,
        })

      }
    })
  },

  // 更多
  morequeue: function (e) {
    console.log(e)
    var that = this;
    this.inqueue.list = this.newlist;
    this.setData({
      inqueue: that.inqueue,
    })
  },

  // 点赞帖子
  likeBtnClick: function (e) {
    var that = this;
    if (e.currentTarget.dataset.type == 1) {
      wx.request({
        url: getApp().globalData.like_common_url,
        data: {
          tid: tid,
          userId: getApp().globalData.userInfo.userId,
          pid: e.currentTarget.dataset.pid,
        },
        success (res) {
          console.log(res)
          that.getForumDetail()
        }
      })


    } else {
      wx.request({
        url: getApp().globalData.topic_liked_url,
        data: {
          tid: tid,
          userId: getApp().globalData.userInfo.userId,
        },
        success (res) {
          console.log(res)
          that.getForumPraise();
        }
      })

      this.setData({
        isLiked: true
      })

    }
  },


  // 查看支持我的人
  supportMePerson: function (e) {
    wx.navigateTo({
      url: '../supportme/supportme?tid=' + tid,
    })
  },

  textAreaChange: function (e) {
    console.log(e)
    this.textAreaString = e.detail.value;
  },

  textareaLineChange: function (e) {
    console.log('--------------------------------------', e)
    wx.pageScrollTo({
      scrollTop: 99999,
      duration: 0,
    })
  },

  // 回复帖子
  replayClick: function (e) {
    console.log(e)
    if (e.currentTarget.id == '0') { // 回复帖子
      this.type = 0;
      this.setData({
        placeHolderText: "我来说两句..."
      })
    } else { // 回复评论
      this.type = 1;
      this.pid = e.currentTarget.dataset.pid;
      this.message = e.currentTarget.dataset.msg;
      this.setData({
        placeHolderText: "回复" + e.currentTarget.dataset.author
      })
    }
    this.setData({
      releaseFocus: true
    })
  },

  cancelReplay: function () {
    this.setData({
      releaseFocus: false,
      textareaValue: ""
    })
  },
  completeBtnReplay: function (e) {
    console.log(e)
    var that = this;
    if (e.type == "confirm") return;
    if (this.textAreaString == undefined || this.textAreaString.length < 1) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return
    }

    wx.showLoading();
    if (this.type == 0) {  
      wx.request({
        url: getApp().globalData.common_reply_url,
        data: {
          tid: tid,
          userId: getApp().globalData.userInfo.userId,
          message: this.textAreaString
        },
        success (res) {
          console.log(res)
          // 刷新品论接口
          that.getForumDetail();
        },
        complete() {
          that.cancelReplay()
          wx.hideLoading()
        }
      })
    } else {
      wx.request({
        url: getApp().globalData.common_reply_url,
        data: {
          tid: tid,
          userId: getApp().globalData.userInfo.userId,
          pid: this.pid,
          oldMsg: this.message,
          message: this.textAreaString
        },
        success(res) {
          console.log(res)
          // 刷新品论接口
          that.getForumDetail();
        },
        complete() {
          that.cancelReplay()
          wx.hideLoading()
        }
      })
    }
    
  },

  // 倒计时方法
  countDown: function (leftTime) {
    var that = this;

    var leftHours = Math.floor(leftTime / 60 / 60);
    if (leftHours<=9) {
      leftHours = '0' + leftHours;
    }
    var leftMinutes = Math.floor(leftTime / 60 % 60);
    if (leftMinutes <= 9) {
      leftMinutes = '0' + leftMinutes;
    }
    var leftSeconds = Math.floor(leftTime % 60);
    if (leftSeconds <= 9) {
      leftSeconds = '0' + leftSeconds;
    }
    that.setData({
      countDownTime: leftHours + ":" + leftMinutes + ":" + leftSeconds,
    })

    if (leftTime > 0) {
      setTimeout(function () {
        leftTime--;
        that.countDown(leftTime);
      }, 1000);
    }
  },

// 开始排队
  startQueueClick: function (e) {
    console.log(e)

    var that = this;
    wx.showLoading()
     wx.request({
       url: getApp().globalData.set_url,
       data: {
         userId: getApp().globalData.userInfo.userId,
         acid: getApp().globalData.acid,
         tid: tid,
         formid: e.detail.formId,
       },
       success (res) {
         console.log(res)
        var data = that.data.data;
        data.status = 2;
        that.setData({
          data: data,
          queueSuccess: true,
          queueData: res.data.data

        })

        that.queueGet();
       },
       complete () {
         wx.hideLoading()
       }
     })
  },

  maskViewClick: function () {
    this.setData({
      queueSuccess: false,
      showYunfei: false
    })
  },

  questionClick: function (e) {
    getApp().globalData.webViewUrl = e.target.dataset.href;
    wx.navigateTo({
      url: '../webview/webview',
    })
  },


  // 查询运费
  queryAmountBtnClick: function () {
    this.setData({
      showYunfei: true
    })
  },

  bindRegionChange: function (e) {
    console.log(e)
    console.log('picker发送选择改变，携带值为', e.detail.value)
    if (e.target.id == 0) {
      this.setData({
        region: e.detail.value
      })
    } else {
      this.setData({
        toRegion: e.detail.value
      })
    }

  },

  weightInputChange: function (e) {
    console.log(e)
    this.setData({
      weight: e.detail.value
    })
  },

  weightChange: function (e) {
    console.log(e)
    this.setData({
      selectorValue: e.detail.value
    })
  },

  queryBtnClick: function () {
    var that = this;

    if (this.data.region == undefined || this.data.region == null || this.data.toRegion == undefined || this.data.toRegion == null) {
      wx.showToast({
        title: '请输入地址进行查询',
        icon: 'none'
      })
      return
    }



    var totalWeight = parseInt(that.data.selectorValue) + 0.5;

    wx.request({
      url: getApp().globalData.calculate_address_amount_url,
      data: {
        fromProvince: that.data.region[0],
        fromCity: that.data.region[1],
        toProvince: that.data.toRegion[0],
        toCity: that.data.toRegion[1],
        totalWeight: totalWeight,
      },
      success(res) {
        console.log(res)
        that.setData({
          addressAmount: res.data.data.amount,
          sz: res.data.data.sz,
          xz: res.data.data.xz,
        })
      }
    })
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    console.log(e)

    if (e.from == 'menu') { // 分享小程序

      return {
        title: '快来加入闲置会发光，做最环保的时髦精>>',
        path: '/pages/login/login',
        imageUrl: '/resources/share_miniprogram.png',
      }
    }

    if (e.target.id == '1') { // 转给适合的朋友
      var title = this.data.data.title;
      if (title.length > 13) {
        title = title.substring(0, 13) + '...'
        console.log(title)
      }

      title = title + "  等你拯救出冷宫>>"

      return {
        title: title,
        path: '/pages/login/login?detail=1&tid=' + tid + '&acid=' + getApp().globalData.acid,
        imageUrl: this.data.data.imageList[0].src,
      }


    } else { // 啦赞

      console.log(getApp().globalData.userInfo.userId, getApp().globalData.acid, tid, getApp().globalData.userInfo.nickName)
      return {
        title: '我正在32个女生衣柜里找新欢，就差你支持了>>',
        path: '/pages/login/login?shareUserId=' + getApp().globalData.userInfo.userId + '&acid=' + getApp().globalData.acid + '&tid=' + tid + '&nickname=' + getApp().globalData.userInfo.nickName,
        imageUrl: '/resources/share_supportme.png',
      }
    }

  }
})
